package com.opoc.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.opoc.config.BaseContext;
import com.opoc.pojo.Result;
import com.opoc.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info(request.toString());
    //从请求头中获取token
    String authHeader = request.getHeader("Authorization");
    String token = null;
    if (authHeader != null && authHeader.startsWith("Bearer ")){
      token = authHeader.substring(7);
    }
    //如果token不存在
    if (!StringUtils.hasLength(token)) {
      Result error = Result.error("NOT_LOGIN");
      //之前返回值是在 RestController 中 会自动转化为JSON数据 这里在过滤器中 所以要自己转化为JSON
      String notLogin = JSONObject.toJSONString(error);
      response.setContentType("application/json");
      response.getWriter().write(notLogin);
      return false;
    }

    //如果token存在 尝试解析token
    try {
      Claims claims = JwtUtils.parseToken(token);
//      log.info(claims.toString());

      BaseContext.setCurrentId(Integer.parseInt(claims.get("admin_id", String.class)));

    } catch (Exception e) {
      e.printStackTrace();
      log.info("token失效");

      Result error = Result.error("NOT_LOGIN");
      String notLogin = JSONObject.toJSONString(error);
      response.setContentType("application/json");
      response.getWriter().write(notLogin);
      return false;
    }

    //放行
    return true;
  }
}
